package teacher;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.*;

// 6. 求2019年上映的电影中，评分最高的3部剧情类电影（电影名，总评分）
public class Score6 {

    public static class Score6Mapper extends Mapper<LongWritable, Text, Text, IntWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split("::");
            String[] split1 = split[3].split("-");
            if (Integer.parseInt(split1[0]) == 2019 && split[5].equals("剧情")) {
                context.write(new Text(split[4]), new IntWritable(Integer.parseInt(split[2]))); // 假设电影名在split[1]，评分在split[2]
            }
        }
    }

    public static class Score6Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {

        private Map<String, Integer> map = new HashMap<>();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }
            map.put(key.toString(), sum);
        }

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            Set<Map.Entry<String, Integer>> set = map.entrySet();
            List<Map.Entry<String, Integer>> list = new ArrayList<>(set);
            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue()); // 降序排序
                }
            });

            int j = 0;
            for (int i = list.size() - 1; j < Math.min(3, list.size()) && i >= 0; i--, j++) {
                context.write(new Text(list.get(i).getKey()), new IntWritable(list.get(i).getValue()));
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration config = new Configuration();
        Job job = Job.getInstance(config);
        job.setJarByClass(Score6.class);
        job.setMapperClass(Score6Mapper.class);
        job.setReducerClass(Score6Reducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileSystem fs = FileSystem.get(config);
        Path inputPath = new Path(Config.TEMP_PATH+"\\part-m-00000");
        Path outputPath = new Path(Config.OUT_PATH[6]);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);
        boolean isDone = job.waitForCompletion(true);
        System.out.println(isDone ? "执行成功" : "执行失败");
    }
}